package com.itheima.springsecureity_demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;

@Configuration
@EnableWebSecurity//开启web安全
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()  //开启http的安全控制
                //.antMatchers("/index.html").permitAll()
                .antMatchers("/login.html").permitAll()
                .antMatchers("/js/**").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()//
                .and()
                .logout()
                .and()
                .formLogin() //设置登录页相关选项
                .loginPage("/login.html")
                .loginProcessingUrl("/login") //登录请求的url地址
                //.usernameParameter("username")
                //.passwordParameter("password")
                .successHandler(new MyAuthenticationSuccessHandler())//
                .failureHandler(new MyAuthenticationFailureHandler())//
                .and().csrf().disable()
                .sessionManagement().maximumSessions(1).expiredUrl("/login.html")
        ;
    }

    @Autowired
    private MyUserDetailServiceImpl myUserDetailService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(myUserDetailService)
                .passwordEncoder(new BCryptPasswordEncoder());
        System.out.println(auth);

    }
    public static void main(String[] args) {
        String encode = new BCryptPasswordEncoder().encode("admin");
        System.out.println(encode);
    }
}
